package com.b2.service.impl;

import com.b2.constant.MessageConstant;
import com.b2.constant.StatusConstant;
import com.b2.context.BaseContext;
import com.b2.mapper.*;
import com.b2.pojo.dto.*;
import com.b2.pojo.entity.Class;
import com.b2.pojo.entity.*;
import com.b2.pojo.vo.OperatedVideoVo;
import com.b2.pojo.vo.ParentVideoInformation;
import com.b2.pojo.vo.TeacherGetworksVo;
import com.b2.properties.AiProperties;
import com.b2.properties.WeChatProperties;
import com.b2.service.ParentVideoService;
import com.b2.service.PushService;
import com.b2.service.TeacherService;
import com.b2.utils.AliOssUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
* @author 悦神
* @description 针对表【parent_video】的数据库操作Service实现
* @createDate 2024-05-14 14:55:27
*/
@Service
public class ParentVideoServiceImpl extends ServiceImpl<ParentVideoMapper, ParentVideo>
    implements ParentVideoService{


    @Autowired
    ParentVideoMapper parentVideoMapper;
    @Autowired
    TeacherVideoMapper teacherVideoMapper;
    @Autowired
    DirectorVideoMapper directorVideoMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    ParentMapper parentMapper;
    @Autowired
    ClassMapper classMapper;
    @Autowired
    VideoMapper videoMapper;
    @Autowired
    private DirectorMapper directorMapper;
    @Autowired
    AliOssUtil aliOssUtil;
    @Autowired
    private PushService pushService;
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private TeacherService teacherService;


    @Autowired
    AiProperties aiProperties;
    @Override
    @Transactional
    public void parentcommitvideo(ParentCommitVideoDto parentCommitVideoDto) {
        ParentVideo parentVideo = new ParentVideo();

       //通过用户id关联得出parentid
        Long currentId = BaseContext.getCurrentId();
        User user = userMapper.selectById(currentId);
        String phone = user.getPhone();
        LambdaQueryWrapper<Parent> o1 = new LambdaQueryWrapper<>();
        o1.eq(Parent::getPhone,phone);
        Parent parent = parentMapper.selectOne(o1);
        Long id = parent.getId();
        //通过classid得到teacherid
        Class aClass = classMapper.selectById(parentCommitVideoDto.getClassId());
        Long teacherId = aClass.getTeacherId();
        if(teacherId==null){
            throw new RuntimeException(MessageConstant.VOID_TEACHER);
        }
        //当前班级没有老师
        parentVideo.setParentId(id);
        parentVideo.setClassId(parentCommitVideoDto.getClassId());
        parentVideo.setVideoId(parentCommitVideoDto.getVideoId());
        parentVideo.setParentVideoUrl(parentCommitVideoDto.getParentVideoUrl());
        parentVideo.setCreateTime(LocalDateTime.now());
        parentVideo.setStatus(StatusConstant.BEFORE_CORRECTION);
        parentVideoMapper.insert(parentVideo);


//        try {
//            //家长上传视频成功后通知给对应的班级老师
//            String accessToken = pushService.refreshAccessToken(weChatProperties.getAppid(),weChatProperties.getSecret());
//            //获取openid
//            //通过teacherId得到对应的openId
//            User teacher = userMapper.selectById(teacherId);
//            String openid = teacher.getOpenid();
//            String templateId = weChatProperties.getTemplateId();
//            String page = "http://picture.mark.syssts.com:9090/classVideo";
//            // 构建订阅消息内容的JSON对象
//            // 构建订阅消息内容的JSON对象
//            JSONObject messageData = new JSONObject();
//            messageData.put("thing4", pushService.createDataItem("课程名称", videoMapper.selectById(parentCommitVideoDto.getVideoId()).getVideoName()));
//            messageData.put("thing5", pushService.createDataItem("教师", teacherService.getById(teacherId).getName()));
//            messageData.put("tiing6", pushService.createDataItem("备注", "您提交的视频已经上线了，欢迎查看！"));
//            messageData.put("time7", pushService.createDataItem("时间", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))));
//            // 将订阅消息内容转换为JSON字符串
//            String jsonData = messageData.toJSONString();
//            pushService.sendSubscribeMessage(accessToken,openid,templateId,page,jsonData);
//        } catch (Exception e) {
//            log.error("发送订阅消息失败: {}", e);
//        }
    }

    @Override
    public ParentVideoInformation getinformation(Long videoid,Long classid) {
        Long currentId = BaseContext.getCurrentId();
        User user = userMapper.selectById(currentId);
        String phone = user.getPhone();
        LambdaQueryWrapper<Parent> o1 = new LambdaQueryWrapper<>();
        o1.eq(Parent::getPhone,phone);
        Parent parent = parentMapper.selectOne(o1);
        Long id = parent.getId();
        //通过classid得到teacherid
        //Class aClass = classMapper.selectById(classid);
        //Long teacherId = aClass.getTeacherId();

        LambdaQueryWrapper<ParentVideo> o2 = new LambdaQueryWrapper<>();
        o2.eq(ParentVideo::getParentId,id);
        o2.eq(ParentVideo::getVideoId,videoid);
        o2.eq(ParentVideo::getClassId,classid);
        ParentVideo parentVideo = parentVideoMapper.selectOne(o2);
        if (parentVideo==null)
        {
            return null;
        }
        ParentVideoInformation parentVideoInformation = new ParentVideoInformation();
        parentVideoInformation.setParentVideoUrl(parentVideo.getParentVideoUrl());
        parentVideoInformation.setTeacherResponse(parentVideo.getTeacherResponse());
        parentVideoInformation.setCreateTime(parentVideo.getCreateTime());
        parentVideoInformation.setId(parentVideo.getId());
        parentVideoInformation.setOverrule(parentVideo.getOverrule());
        parentVideoInformation.setStatus(parentVideo.getStatus());
        parentVideoInformation.setAiResponse(parentVideo.getAiResponse());
        return parentVideoInformation;
    }

    @Override
    public Integer getstatus(Long id) {
        ParentVideo parentVideo = parentVideoMapper.selectById(id);
        if(parentVideo.getStatus()==1){
            parentVideo.setStatus(100);
            parentVideoMapper.updateById(parentVideo);
        }
        return parentVideo.getStatus();
    }

    @Override
    @Transactional
    public void parentupdatevideo(ParentUpdateVideoDto parentUpdateVideoDto) {

       //批改后用户不能修改
        ParentVideo parentVideo1 = parentVideoMapper.selectById(parentUpdateVideoDto.getId());
        if (parentVideo1.getStatus()==1) {
            throw new RuntimeException(MessageConstant.UPDATE_FAIL);
        }

        ParentVideo parentVideo = new ParentVideo();

        parentVideo.setId(parentUpdateVideoDto.getId());

        parentVideo.setParentVideoUrl(parentUpdateVideoDto.getNewparentVideoUrl());
        //修改后将状态设置为未批改
        parentVideo.setStatus(StatusConstant.BEFORE_CORRECTION);

        parentVideoMapper.updateById(parentVideo);

        aliOssUtil.deleteFile(parentUpdateVideoDto.getOldparentVideoUrl());
    }

    @Override
    public List<TeacherGetworksVo> teahcergetworks(TeacherGetWorksDto teacherGetWorksDto) {

        LambdaQueryWrapper<ParentVideo> o = new LambdaQueryWrapper<>();
        o.eq(ParentVideo::getClassId,teacherGetWorksDto.getClassId());
        o.eq(teacherGetWorksDto.getStatus()!=null,ParentVideo::getStatus,teacherGetWorksDto.getStatus());
        List<ParentVideo> parentVideos = parentVideoMapper.selectList(o);
        List<TeacherGetworksVo> teacherGetworksVos = new ArrayList<>();
        for (ParentVideo p:parentVideos) {

            Long parentId = p.getParentId();
            Parent parent = parentMapper.selectById(parentId);
            Video video = videoMapper.selectById(p.getVideoId());
            if (video==null) {
                continue;
            }

            TeacherGetworksVo teacherGetworksVo = new TeacherGetworksVo();
            teacherGetworksVo.setId(p.getId());
            teacherGetworksVo.setParentVideoUrl(p.getParentVideoUrl());
            teacherGetworksVo.setTeacherResponse(p.getTeacherResponse());
            teacherGetworksVo.setCreateTime(p.getCreateTime());
            teacherGetworksVo.setParentname(parent.getName());
            teacherGetworksVo.setVideoname(video.getVideoName());
            teacherGetworksVo.setStatus(p.getStatus());
            teacherGetworksVo.setOverrule(p.getOverrule());
            teacherGetworksVos.add(teacherGetworksVo);
        }
        return teacherGetworksVos;
    }

    @Override
    @Transactional
    public String getAiresponse(AiDto aiDto) {
        ParentVideo parentVideo = new ParentVideo();

        String post;
        try {
            post = this.post(aiProperties.getAiUrl(), aiDto.getImageUrl());

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        parentVideo.setId(aiDto.getId());
        parentVideo.setTeacherPictureUrl(aiDto.getImageUrl());
        parentVideo.setAiResponse(post.toString());
        parentVideoMapper.updateById(parentVideo);
     //  if (true)
     //   throw new RuntimeException("ss");
        return post.toString();
    }

    @Override
    public void putTeacherResponse(TeacherResponseDto teacherResponseDto) {

        //驳回状态不可批改
        ParentVideo parentVideo1 = parentVideoMapper.selectById(teacherResponseDto.getId());
        if (parentVideo1.getStatus()==2) {
            throw new RuntimeException(MessageConstant.RESPONSE_FAIL);
        }


        ParentVideo parentVideo = new ParentVideo();
        parentVideo.setId(teacherResponseDto.getId());
        parentVideo.setTeacherResponse(teacherResponseDto.getResponse());
      //评论后将工作设置为已完成
        parentVideo.setStatus(StatusConstant.AFTER_CORRECTION);
        parentVideoMapper.updateById(parentVideo);
    }

    @Override
    @Transactional
    public void TeacherUpdateStatus(Long id,String overrule) {

        ParentVideo parentVideo = new ParentVideo();
        ParentVideo parentVideo1 = parentVideoMapper.selectById(id);

       //批改后不能驳回
        if (parentVideo1.getStatus()==1) {
            throw new RuntimeException(MessageConstant.STATUS_FAIL);
        }
        parentVideo.setId(id);
        parentVideo.setStatus(StatusConstant.FAIL);
        parentVideo.setOverrule(overrule);
        parentVideoMapper.updateById(parentVideo);
    }

    @Override
    public List<OperatedVideoVo> GetOperatedVideo(Integer status, String name) {

        if (name .equals( "家长")) {
            Long currentId = BaseContext.getCurrentId();

            LambdaQueryWrapper<ParentVideo> p = new LambdaQueryWrapper<>();
            p.eq(ParentVideo::getParentId, currentId);
            p.eq(ParentVideo::getStatus, status);
            List<ParentVideo> parentVideos = parentVideoMapper.selectList(p);
            ArrayList<OperatedVideoVo> operatedVideoVos = new ArrayList<>();
            for (ParentVideo parentVideo : parentVideos
            ) {
                OperatedVideoVo operatedVideoVo = new OperatedVideoVo();
                operatedVideoVo.setVideoId(parentVideo.getVideoId());
                operatedVideoVo.setClassId(parentVideo.getClassId());
                Video video = videoMapper.selectById(parentVideo.getVideoId());
                operatedVideoVo.setVideoName(video.getVideoName());
                operatedVideoVos.add(operatedVideoVo);
            }
            return operatedVideoVos;
        }
        if (name .equals( "老师")) {
            Long currentId = BaseContext.getCurrentId();
            LambdaQueryWrapper<TeacherVideo> p = new LambdaQueryWrapper<>();
            p.eq(TeacherVideo::getTeacherId, currentId);
            p.eq(TeacherVideo::getStatus, status);
            List<TeacherVideo> teacherVideos =teacherVideoMapper .selectList(p);
            ArrayList<OperatedVideoVo> operatedVideoVos = new ArrayList<>();
            for (TeacherVideo teacherVideo : teacherVideos
            ) {
                OperatedVideoVo operatedVideoVo = new OperatedVideoVo();
                operatedVideoVo.setVideoId(teacherVideo.getVideoId());
                operatedVideoVo.setClassId(teacherVideo.getClassId());
                Video video = videoMapper.selectById(teacherVideo.getVideoId());
                operatedVideoVo.setVideoName(video.getVideoName());
                operatedVideoVos.add(operatedVideoVo);
            }
            return operatedVideoVos;
        }
        if (name.equals( "园长")) {

            //因为园长身份为自己录入，园长id与用户id不匹配，所有需要我们用手机号进行绑定身份
            Long currentId = BaseContext.getCurrentId();
            User user = userMapper.selectById(currentId);
            String phone = user.getPhone();
            LambdaQueryWrapper<Director> o1 = new LambdaQueryWrapper<>();
            o1.eq(Director::getPhone,phone);
            Director director = directorMapper.selectOne(o1);
            Long id = director.getId();
            LambdaQueryWrapper<DirectorVideo> p = new LambdaQueryWrapper<>();
            p.eq(DirectorVideo::getDirectorId, id);
            p.eq(DirectorVideo::getStatus, status);
            List<DirectorVideo> directorVideos =directorVideoMapper .selectList(p);
            ArrayList<OperatedVideoVo> operatedVideoVos = new ArrayList<>();
            for (DirectorVideo directorVideo : directorVideos
            ) {
                OperatedVideoVo operatedVideoVo = new OperatedVideoVo();
                operatedVideoVo.setVideoId(directorVideo.getVideoId());
                Video video = videoMapper.selectById(directorVideo.getVideoId());
                operatedVideoVo.setVideoName(video.getVideoName());
                operatedVideoVos.add(operatedVideoVo);
            }
            return operatedVideoVos;
        }
        System.out.println("请求错误");
        System.out.println(name);
        System.out.println(status);
        return  null;
    }
    //向ai服务器发送请求
    private String post(String postURL,String name) throws Exception {
        PostMethod postMethod = new PostMethod(postURL);
        postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        //参数设置，需要注意的就是里边不能传NULL，要传空字符串
        NameValuePair[] data = {
                new NameValuePair("image", name)
        };
        postMethod.setRequestBody(data);
        org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
        httpClient.executeMethod(postMethod);
        String result = postMethod.getResponseBodyAsString();
        System.out.println(result.toString());
        return result;

    }
}




